<template>
  <div>
    <Breadcrumb :opt-data="modelOptData"></Breadcrumb>
    <PageLayout>
      <div class="table-container height-100">
        <EZTable
          v-loading="tableLoading"
          :table-id="tableId"
          :table-hdl="tableHdl"
          :rows="modelData"
          :selectable="true"
          :custom-empty="true"
          @pageChanged="getModelData"
          @sizeChanged="getModelData"
          @filterChange="getModelData"
          @selectionChange="(data) => this.selectModelData = data">
          <div slot="customOpts">
            <el-tooltip v-if="selectModelData.length > 0" :open-delay="300" placement="left">
              <div slot="content">
                <div v-for="model in selectModelData" :key="model._id">{{model.detailName}}</div>
              </div>
              <div class="display-inline">
                <span>已选择 </span>
                <span class="font-color-primary">{{selectModelData.length}}</span>
                <span> 条</span>
              </div>
            </el-tooltip>
          </div>
          <EmptyContent slot="empty" :opt-data="modelOptData"></EmptyContent>
        </EZTable>
      </div>
      <el-dialog
        :title="`${!isEditModel ? '新增' : '编辑'}型号`"
        :visible.sync="showModelDialog"
        :close-on-click-modal="false"
        width="600px"
        center>
        <el-form
          v-loading="modelFormLoading"
          :ref="modelFormRef"
          :model="modelForm"
          :rules="modelFormRules"
          size="small"
          label-width="130px">
          <el-form-item label="设备类型" prop="deviceType">
            <el-select v-model="modelForm.deviceType" clearable filterable class="width-100"
                       placeholder="请选择设备类型">
              <el-option :label="deviceType.name" :value="deviceType._id" :key="idx"
                         v-for="(deviceType, idx) in deviceTypeData"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备厂家" prop="manufacturer">
            <el-select v-model="modelForm.manufacturer" clearable filterable class="width-100"
                       placeholder="请选择设备厂家"
                       @change="manufacturerChanged">
              <el-option :label="manufacturer.label" :value="manufacturer.value" :key="idx"
                         v-for="(manufacturer, idx) in manufacturerData"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="设备系列" prop="series">
            <el-select v-model="modelForm.series" clearable filterable class="width-100" placeholder="请选择设备系列">
              <el-option :label="series.label" :value="series.value" :key="idx"
                         v-for="(series, idx) in seriesData"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="型号名" prop="name">
            <el-input v-model="modelForm.name" placeholder="请填写型号名"></el-input>
          </el-form-item>
          <el-form-item label="备注">
            <el-input type="textarea" v-model="modelForm.remarks" placeholder="请填写备注"></el-input>
          </el-form-item>
          <div class="text-align-right">
            <el-form-item>
              <el-button size="medium" @click="modelFormCanceled">取消</el-button>
              <el-button size="medium" type="primary" @click="modelFormSubmitted">提交</el-button>
            </el-form-item>
          </div>
        </el-form>
      </el-dialog>
    </PageLayout>
  </div>
</template>

<script>
  import {msgCode} from "@/config/string";
  import {tableIdConfig, tableOptBtnConfig} from '@/config/table';
  import {confirmHandle, deepCopyWithJson, messageHandle} from "@/utils";
  import {assembleTableOptBtn, getTableConfig, TableStateHdl} from "@/modules/routeParamStateHdl";
  import modelTableCfg from "../../config/table/model";
  import EZTable from '../../components/table/EZTable';

  export default {
    name: "DeviceModel",
    components: {
      EZTable
    },
    data() {
      return {
        tableLoading: true,
        tableId: tableIdConfig.model,
        tableHdl: null,
        modelData: [],
        showModelDialog: false,
        modelFormLoading: false,
        deviceTypeData: [],
        manufacturerData: [],
        seriesData: [],
        modelForm: {},
        modelFormRules: {
          deviceType: [
            {required: true, message: '请选择设备类型', trigger: 'blur'}
          ],
          manufacturer: [
            {required: true, message: '请选择设备厂家', trigger: 'blur'}
          ],
          series: [
            {required: true, message: '请选择设备系列', trigger: 'blur'}
          ],
          name: [
            {required: true, message: '请填写型号名', trigger: 'blur'}
          ],
        },
        modelFormRef: 'modelFormRef',
        isEditModel: false,
        selectModelData: []
      }
    },
    computed: {
      modelOptData() {
        return [
          {
            type: 'btn',
            label: '新增型号',
            icon: 'icon-tianjia',
            callback: () => {
              this.clickCreateBtn();
            }
          }
        ];
      }
    },
    activated() {
      this.initTableConfig();
      this.initModelForm();
      this.getDeviceTypeData();
      this.getManufacturerData();
      // this.getSeriesData();
      this.getModelData();
    },
    methods: {
      initTableConfig() {
        if (this.tableHdl) return;
        const {columns = [], filters = []} = getTableConfig(this.tableId, modelTableCfg);
        assembleTableOptBtn(columns, ({type = '', data = {}}) => {
          if (!type) return;
          const model = deepCopyWithJson(data);
          switch (type) {
            case tableOptBtnConfig.edit.type:
              this.showModelDialog = true;
              this.isEditModel = true;
              this.modelForm = model;
              this.getSeriesData(model.manufacturer);
              break;
            case tableOptBtnConfig.delete.type:
              this.deleteModel(model);
              break;
            default:
              break;
          }
        });
        this.tableHdl = new TableStateHdl(this.$route.name, this.tableId, columns, filters);
      },
      initModelForm() {
        this.modelForm = {
          deviceType: '',
          manufacturer: '',
          series: '',
          name: '',
          remarks: '',
        }
      },
      resetModelForm() {
        this.initModelForm();
        const modelForm = this.$refs[this.modelFormRef];
        modelForm && modelForm.resetFields();
      },
      clickCreateBtn() {
        this.isEditModel && this.resetModelForm();
        this.showModelDialog = true;
        this.isEditModel = false;
      },
      getDeviceTypeData() {
        API.deviceType.deviceTypeAll().then(result => {
          const {data = []} = result;
          this.deviceTypeData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      getManufacturerData() {
        API.manufacturer.manufacturerAll().then(result => {
          const {data = []} = result;
          this.manufacturerData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      manufacturerChanged(id) {
        this.modelForm.series = ''
        this.getSeriesData(id);
      },
      getSeriesData(id) {
        API.series.seriesManufacturer({id: id}).then(result => {
          const {data = []} = result;
          this.seriesData = data;
        }).catch(err => {
          console.log('err', err)
        });
      },
      getModelData() {
        this.tableLoading = true;
        const selector = {};
        const tableParam = this.tableHdl.assembleTableParam();
        API.model.modelList({...tableParam, selector}).then(result => {
          this.tableLoading = false;
          const {data = [], total = 0} = result;
          this.modelData = data;
          this.tableHdl.total = total;
        }).catch(err => {
          console.log('err', err)
          this.tableLoading = false;
        });
      },
      deleteModel(model = {}) {
        confirmHandle({label: `确定要删除型号：${model.name} 吗?`}).then(() => {
          API.model.modelDelete({_id: model._id}).then(result => {
            messageHandle({code: msgCode.DELETE_SUCCESS, title: '型号'});
            this.tableHdl.judgeTableMatched();
            this.getModelData();
            this.resetModelForm();
          });
        }).catch(() => {
        });
      },
      modelFormCanceled() {
        this.showModelDialog = false;
      },
      modelFormSubmitted() {
        this.$refs[this.modelFormRef].validate((valid) => {
          if (!valid) return;
          this.modelFormLoading = true;
          if (!this.isEditModel) {
            API.model.modelAdd({...this.modelForm}).then(result => {
              messageHandle({code: msgCode.ADD_SUCCESS, title: '型号'});
              this.showModelDialog = false;
              this.modelFormLoading = false;
              this.getModelData();
              this.resetModelForm();
            }).catch(err => {
              console.log('err', err)
              this.modelFormLoading = false;
            });
          } else {
            API.model.modelEdit({...this.modelForm}).then(result => {
              messageHandle({code: msgCode.EDIT_SUCCESS, title: '型号'});
              this.showModelDialog = false;
              this.modelFormLoading = false;
              this.getModelData();
              this.resetModelForm();
            }).catch(err => {
              console.log('err', err)
              this.modelFormLoading = false;
            });
          }
        });
      },
    },
  }
</script>

<style scoped>

</style>
